using System;
using System.Text;
using Microsoft.SPOT;

/*
 * Message Format 
 * SourceDeviceID|TargetDeviceID|Command|ParamsCount|Optional n...Params\r\n
 * 
 * Source and Target Device ID can be Host, Cobra, Panda
 * Command see Command Class
 * 
 * 
 */
namespace CobraController
{

  public static class MessageHandler
  {
    public static MTS ParseMessage(string message)
    {
      Message Mes = new Message();
      if (message.IndexOf("\r\n") > 0)
      { 
      message = message.Substring(0, message.Length-2);
      } 
      string[] MessageParams = message.Split('|');
      Mes.SenderID = MessageParams[0];
      Mes.TargetID = MessageParams[1];
      Mes.Command = MessageParams[2];
      Mes.ParamsCount = Convert.ToInt32(MessageParams[3]);
      if (Mes.ParamsCount > 0)
      {
        Mes.Params = new string[Mes.ParamsCount];
        for (int x = 0; x < Mes.ParamsCount; x++)
        {
          Mes.Params[x] = MessageParams[4+x];
        }
      }

      MTS mts = new MTS();

      // HAMS to PANDA: forward message to PANDA
      if (Mes.SenderID == ID.HAMS & Mes.TargetID == ID.PANDA)
      {
        Debug.Print("Hams to Panda");
        mts.MyMessage = Mes;
        mts.MyTransport = Transport.SER;
      }

      // PANDA to HAMS: forward message to HAMS
      if (Mes.SenderID == ID.PANDA & Mes.TargetID == ID.HAMS)
      {
        Debug.Print("Panda to Hams");
        mts.MyMessage = Mes;
        mts.MyTransport = Transport.NET;
      }


      // HAMS to COBRA
      if (Mes.SenderID == ID.HAMS & Mes.TargetID == ID.COBRA)
      {
				mts.MyMessage = Mes;
				mts.MyTransport = Transport.LOC;
      }

      // COBRA to HAMS
      if (Mes.SenderID == ID.COBRA & Mes.TargetID == ID.HAMS)
      {
				mts.MyMessage = Mes;
				mts.MyTransport = Transport.LOC;

      }

      return mts;
    }

    //public static void ProcessMessage(Message msg)
    //{ 
    //  //Only for HAMS to Cobra

    //}

    //private static void Action(string[] message)
    //{
    //  if (message[0] == "elro")
    //  {
    //    RF433.SendCode(message[1], message[2], message[3]=="on"? true: false);
    //  }
    //}

    //public static byte[] SendMessage(string msg)
    //{
    //  return Encoding.UTF8.GetBytes(DateTime.Now.ToString() + "," + msg);
    //}



  }
}
